package com.sourcemuch.im.caiba;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import cn.wildfire.chat.app.extendsion.ui.ScreenListener;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.kit.WfcUIKit;
import cn.wildfire.chat.kit.voip.SingleVoipCallActivity;
import cn.wildfirechat.client.IRemoteClient;
import cn.wildfirechat.remote.ChatManager;

/**
 * Create by HEKE, 2019/8/20 17:19
 * TODO 高级别服务，用于建立及时通信对象
 */
public class SuperService extends Service {

    public static final String CHANNEL_ID = "caiba_notification_id";
    public static String CHANNEL_NAME;

    protected CaiBaChatApp caiBaChatApp;
    private CaibaBinder caibaBinder;
    private boolean running = false;
    private CaibaPersistentThread caibaPersistentThread;

    private OnCaiBaPersistentListener onCaiBaPersistentListener;
    private int seconds; // 应用程序存活时间，单位秒

    /**
     * modify by HEKE , 2019/8/21 9:58
     * TODO 捆绑信息交互对象，避免被系统回收
     */
    private WfcUIKit wfcUIKit;
    private IRemoteClient remoteClient;

    /**
     * 操作消息对象
     */
    private Handler mHandler;

    /**
     * 屏幕监听对象
     */
    ScreenListener screenListener;
    protected boolean isScreenOff;

    /**
     * 用户是否手动操作APP系统消息开关
     */
    protected boolean isNotifyOn;
    protected boolean notifyOld;
    protected boolean canReqListener;

    /**
     * 手动捆绑刷新事件对象
     */
    public ManumotiveIBinder manumotiveIBinder;

    /**
     * 唯一通知入口
     */
    protected NotificationManager notificationManager;
    protected Notification persistentNoi;
    protected NotificationCompat.Builder builder;

    public SuperService() {
        super();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        CHANNEL_NAME = getResources().getString(R.string.super_service_title);
        caiBaChatApp = (CaiBaChatApp) getApplicationContext();
        caibaBinder = new CaibaBinder();
        notificationManager = (NotificationManager) caiBaChatApp.getSystemService(Context.NOTIFICATION_SERVICE);
        manumotiveIBinder = caiBaChatApp.manumotiveIBinder;
        wfcUIKit = caiBaChatApp.wfcUIKit;
        running = true;
        seconds = 0;
        mHandler = CaiBaChatApp.getMainHandler();
        isNotifyOn = isNotificationEnabled(getApplicationContext());
        notifyOld = isNotifyOn;
        // 绑定手机锁屏等操作
        screenListener = new ScreenListener(this);
        screenListener.begin(new ScreenListener.ScreenStateListener() {
            @Override
            public void onScreenOn() {
                isScreenOff = false;
                caiBaChatApp.isScreenLocked = false;
                if (caiBaChatApp.lightThenNotifyPhone != null) {
                    caiBaChatApp.lightThenNotifyPhone.hideWindow();
                }
            }

            @Override
            public void onScreenOff() {
                isScreenOff = true;
                caiBaChatApp.isScreenLocked = true;
                if (caiBaChatApp.lightThenNotifyPhone != null) {
                    caiBaChatApp.lightThenNotifyPhone.showWindow();
                }
            }

            @Override
            public void onUserPresent() {
                isScreenOff = false;
                caiBaChatApp.isScreenLocked = false;
                if (caiBaChatApp.lightThenNotifyPhone != null) {
                    caiBaChatApp.lightThenNotifyPhone.hideWindow();
                }
            }
        });
    }

    /**
     * 判断当前程序是否开启应用通知
     */
    private boolean isNotificationEnabled(Context context) {
        boolean isOpened = false;
        try {
            isOpened = NotificationManagerCompat.from(context).areNotificationsEnabled();
        } catch (Exception e) {
            e.printStackTrace();
            isOpened = false;
        }
        return isOpened;
    }

    /**
     * Create by HEKE, 2019/8/20 19:20
     * TODO 连接服务对象
     */
    public class CaibaBinder extends Binder {

        /**
         * 绑定持续交互接口
         *
         * @param onCaiBaPersistentListener
         */
        public void bindListener(OnCaiBaPersistentListener onCaiBaPersistentListener) {
            SuperService.this.onCaiBaPersistentListener = onCaiBaPersistentListener;
        }

        /**
         * 绑定IM主控制对象
         *
         * @param wfcUIKit
         */
        public void bindPushObject(WfcUIKit wfcUIKit) {
            //SuperService.this.wfcUIKit = wfcUIKit;
        }

        /**
         * 发送通知入口
         *
         * @param content 通知内容
         */
        public void pushNotify(String content) {
            if (TextUtils.isTextEmpty(content)) {
                return;
            }
            NotificationCompat.Builder builder = getNotification(getString(R.string.app_name), content);
            notificationManager.notify(110, builder.build());
        }

        /**
         * 关闭服务前释放捆绑数据对象
         */
        public void release() {
            try {
                caibaPersistentThread.shutdown();
                caibaPersistentThread = null;
                onCaiBaPersistentListener = null;
                wfcUIKit = null;
                mHandler = null;
                remoteClient = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * Create by HEKE, 2019/8/20 19:24
     * TODO 持续交互接口
     */
    public interface OnCaiBaPersistentListener {
        void alive(int seconds);

        void refreshObserversReq();
    }

    /**
     * Create by HEKE, 2019/8/20 19:21
     * TODO 服务启动后持续运行线程
     */
    private class CaibaPersistentThread extends Thread {

        private boolean tclosed;
        private int count;

        public void shutdown() {
            tclosed = true;
        }

        @Override
        public void run() {
            super.run();
            while (running) {
                try {
                    Thread.sleep(500);
                    if (tclosed) {
                        running = false;
                        break;
                    }
                    seconds++;
                    // 持续获取引用交互
                    try {
                        count++;
                        if (count >= 120) {
                            count = 0;
                            try {
                                if (onCaiBaPersistentListener != null) {
                                    onCaiBaPersistentListener.alive(seconds);
                                }
                                /**
                                 * 强制后台连接
                                 * */
                                manumotiveIBinder.postRun(new Runnable() {
                                    @Override
                                    public void run() {
                                        ChatManager.Instance().forceConnect();
                                    }
                                }, 0);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // 执行检测系统通知开关是否不同
                    checkNotifySwitch();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 由于开关设置系统的APP通知，允许手动刷新一分钟
     */
    protected int canNotifyCount;

    /**
     * TODO 即时检测通知开关(手机系统APP通知开关影响消息刷新，维持一分钟的方式保障消息正常)
     */
    private void checkNotifySwitch() {
        notifyOld = isNotifyOn;
        isNotifyOn = isNotificationEnabled(getApplicationContext());
        // 两边状态不同时刷新监听
        if (!(String.valueOf(notifyOld).equals(String.valueOf(isNotifyOn)))) {
            canReqListener = true;
            notifyOld = isNotifyOn;
        }
        if (canReqListener) {
            canNotifyCount++;
            if (canNotifyCount > 120) {
                canReqListener = false;
                canNotifyCount = 0;
            }
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (onCaiBaPersistentListener != null) {
                        onCaiBaPersistentListener.refreshObserversReq();
                    }
                }
            });
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            // 启动持续交互线程
            if (caibaPersistentThread == null) {
                ((CaiBaChatApp) getApplicationContext()).bindCaibaBinder(caibaBinder);
                caibaPersistentThread = new CaibaPersistentThread();
                caibaPersistentThread.start();
            }
            // 发送常驻状态栏通知
            if (persistentNoi == null) {
                persistentNoi = getNotification(getString(R.string.app_name), "服务正在运行中").build();
                startForeground(110, persistentNoi);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * modify by HEKE , 2019/8/20 20:53
     * <p>
     * TODO 创建通知构造对象
     */
    private NotificationCompat.Builder getNotification(String title, String content) {
        NotificationCompat.Builder builder = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setSound(null, null);
            manager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
            builder.setPriority(NotificationCompat.PRIORITY_MAX);
        } else {
            builder = new NotificationCompat.Builder(this, CHANNEL_ID);
            builder.setPriority(NotificationCompat.PRIORITY_MAX);
            builder.setSound(null);
        }
        /**
         * SingleVoipCallActivity 默认设定通话界面为唤醒入口。若程序被杀死，程序将重新启动。
         * */
        Intent nfIntent = new Intent(this, SingleVoipCallActivity.class);
        builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0));
        builder.setContentTitle(title);
        builder.setContentText(content);
        builder.setSmallIcon(R.mipmap.ic_launcher_cailiao);
        builder.setWhen(System.currentTimeMillis());
        builder.setAutoCancel(false);
        SuperService.this.builder = builder;
        return builder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        running = false;
        stopForeground(true);
        if (screenListener != null) {
            screenListener.unregisterListener();
        }
        Log.e("Service", "onDestroy");
    }

}